import axios from "axios"
import qs from "qs"
import { Notification } from "element-ui"
import { baseURL } from "@/config/baseURL"

const httpRequest = axios.create({
  baseURL: baseURL,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    authorization: "admin"
  },
  params: {}
})

// 添加请求拦截器
httpRequest.interceptors.request.use(
  config => {
    config.params = {
      ...config.params
    }
    // config.data = {
    //   // ...config.data
    //   qs.stringify(...config.data)
    // }
    config.data = qs.stringify(config.data)
    return config
  },
  error => Promise.reject(error)
)

// 添加响应拦截器
httpRequest.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const res = response.data
      if (res.code === 200) {
        return res
      } else {
        Notification.error({
          title: `错误码：${res.code}`,
          message: `${res.message}`
        })
        return Promise.reject(res)
      }
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default httpRequest
